import { IAuthLoader } from '@/router/AuthLoader'
import { searchRoute } from '@/utils'
import { Tabs } from 'antd'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
interface TabsItem {
  key: string
  label: string
  closable: boolean
}
export default function TabsFC() {
  const { pathname } = useLocation() // **** 路由路径
  const [tabsList, setTabsList] = useState<TabsItem[]>([
    {
      key: '/welcome',
      label: '首页',
      closable: false // **** 不可删除
    }
  ])
  const [activeKey, setActiveKey] = useState('') // 激活
  const data = useRouteLoaderData('layout') as IAuthLoader // loader
  const navigate = useNavigate()

  // 监听路由路径变化
  useEffect(() => {
    addTabs()
  }, [pathname])

  // 创建页签
  const addTabs = () => {
    const route = searchRoute(pathname, data.menuList) // 找到当前页面的路由信息
    if (!route) return
    // 没有匹配到跳到欢迎
    if (!tabsList.find(item => item.key == route.path)) {
      tabsList.push({
        key: route.path,
        label: route.menuName,
        // closable: pathname !== '/welcome'
        closable: true
      })
    }
    setTabsList([...tabsList])
    setActiveKey(pathname)
  }

  // 路由切换
  const handleChange = (path: string) => {
    navigate(path)
  }

  // 删除
  const handleDel = (path: string) => {
    if (pathname === path) {
      // **** 删除后跳转最近的页面
      tabsList.forEach((item, index: number) => {
        if (item.key != pathname) return // 删除其他
        const nextTab = tabsList[index + 1] || tabsList[index - 1]
        // if (!nextTab) return
        navigate(nextTab.key)
      })
    }
    setTabsList(tabsList.filter(item => item.key != path)) // 重新遍历 ****
  }

  return (
    <Tabs
      activeKey={activeKey}
      items={tabsList}
      tabBarStyle={{ height: 40, marginBottom: 0, backgroundColor: 'var(--bg-color)' }}
      type='editable-card' // 样式类型
      hideAdd // 隐藏添加按钮
      onChange={handleChange} // 路由切换
      onEdit={path => {
        handleDel(path as string) // 删除
      }}
    />
  )
}
